from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
from django.db.models import Q
from django.utils.decorators import method_decorator
from django.views.decorators.http import require_http_methods
from user.middleware import JwtAuthenticationMiddleware
from .models import StudentScore
from .serializer import StudentScoreSerializer, StudentScoreListSerializer
from user.response_code import response_code
import json


# Create your views here.
class ListAllView(View):
    def get(self, request):  # 查询一般用get请求
        obj_scoreList = StudentScore.objects.all().values()  # 化为字典
        scoreList = list(obj_scoreList)  # 化为列表
        return JsonResponse(
            {"code": 200, "message": "查询成功", "scoreList": scoreList}
        )


@csrf_exempt
@require_http_methods(["POST"])
def score_list(request):
    """获取成绩列表"""
    try:
        data = json.loads(request.body)
        query = data.get("query", "")
        page_num = data.get("pageNum", 1)
        page_size = data.get("pageSize", 10)

        # 构建查询条件
        q_objects = Q()
        if query:
            q_objects = Q(student_id__icontains=query) | Q(
                student_name__icontains=query
            )

        # 查询数据
        queryset = StudentScore.objects.filter(q_objects).order_by(
            "-exam_date", "student_id"
        )

        # 分页
        total = queryset.count()
        start = (page_num - 1) * page_size
        end = start + page_size
        scores = queryset[start:end]

        # 序列化数据
        serializer = StudentScoreListSerializer(scores, many=True)

        return response_code.resp_200({"scoreList": serializer.data, "total": total})
    except Exception as e:
        return response_code.resp_400(str(e))


@csrf_exempt
@require_http_methods(["POST"])
def score_add(request):
    """添加成绩"""
    try:
        data = json.loads(request.body)
        serializer = StudentScoreSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return response_code.resp_200({"message": "添加成功"})
        else:
            return response_code.resp_400(str(serializer.errors))
    except Exception as e:
        return response_code.resp_400(str(e))


@csrf_exempt
@require_http_methods(["POST"])
def score_update(request):
    """更新成绩"""
    try:
        data = json.loads(request.body)
        score_id = data.get("id")

        if not score_id:
            return response_code.resp_400("缺少成绩ID")

        try:
            score = StudentScore.objects.get(id=score_id)
        except StudentScore.DoesNotExist:
            return response_code.resp_400("成绩记录不存在")

        serializer = StudentScoreSerializer(score, data=data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return response_code.resp_200({"message": "更新成功"})
        else:
            return response_code.resp_400(str(serializer.errors))
    except Exception as e:
        return response_code.resp_400(str(e))


@csrf_exempt
@require_http_methods(["POST"])
def score_delete(request):
    """删除成绩"""
    try:
        data = json.loads(request.body)
        score_id = data.get("id")

        if not score_id:
            return response_code.resp_400("缺少成绩ID")

        try:
            score = StudentScore.objects.get(id=score_id)
            score.delete()
            return response_code.resp_200({"message": "删除成功"})
        except StudentScore.DoesNotExist:
            return response_code.resp_400("成绩记录不存在")
    except Exception as e:
        return response_code.resp_400(str(e))


@csrf_exempt
@require_http_methods(["POST"])
def score_detail(request):
    """获取成绩详情"""
    try:
        data = json.loads(request.body)
        score_id = data.get("id")

        if not score_id:
            return response_code.resp_400("缺少成绩ID")

        try:
            score = StudentScore.objects.get(id=score_id)
            serializer = StudentScoreSerializer(score)
            return response_code.resp_200(serializer.data)
        except StudentScore.DoesNotExist:
            return response_code.resp_400("成绩记录不存在")
    except Exception as e:
        return response_code.resp_400(str(e))
